package models

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"week_three/user_srv/common/global"
)

func InitMysql(mysqlFunc func(DB *gorm.DB) error) error {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		global.UserConfig.MysqlConf.Username, global.UserConfig.MysqlConf.Password, global.UserConfig.MysqlConf.Host, global.UserConfig.MysqlConf.Port, global.UserConfig.MysqlConf.Database,
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})
	if err != nil {
		panic(err)
	}
	tx, _ := db.DB()
	defer tx.Close()
	return mysqlFunc(db)
}

func DatabaseMigrate() error {
	return InitMysql(func(DB *gorm.DB) error {
		return DB.AutoMigrate(&User{})
	})

}

type User struct {
	gorm.Model
	Username string
	Password string
}
